<?php

/**
 * @name WechatController
 * @desc 控制器
 */
define("TOKEN", "vmall");
class WechatController extends ApiBaseController
{
    /**
     * 默认动作
     */
    public function indexAction()
    {
        $this->responseMsg();
    }

    public function responseMsg(){

//        $xml_str = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml_str = file_get_contents("php://input");
        if(empty($xml_str)){
            die('');
        }
        if(!empty($xml_str)){
            // 解析该xml字符串，利用simpleXML
            libxml_disable_entity_loader(true);
            //禁止xml实体解析，防止xml注入
            $request_xml = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);

//            $accessTokenModel = \AccessTokenModel::getSingleton();
//            $accessTokenModel->add([
//                'app_id'    => $request_xml->EventKey,
//                'access_token'  => substr($xml_str, 0,100),
//                'expires_time'  => time()
//            ]);

            //判断该消息的类型，通过元素MsgType
            switch ($request_xml->MsgType){
                case 'event':
                    //判断具体的时间类型（关注、取消、点击）
                    $event = $request_xml->Event;
                    if ($event=='subscribe') { // 关注事件
                        $this->doSubscribe($request_xml);
                    }elseif ($event=='CLICK') {//菜单点击事件
                        $this->doClick($request_xml);
                    }elseif ($event=='VIEW') {//连接跳转事件
                        $this->doView($request_xml);
                    }
                    break;
                case 'text'://文本消息
                    $this->doText($request_xml);
                    break;
                case 'image'://图片消息
                    $this->doImage($request_xml);
                    break;
                case 'voice'://语音消息
                    $this->doVoice($request_xml);
                    break;
                case 'video'://视频消息
                    $this->_doVideo($request_xml);
                    break;
                case 'shortvideo'://短视频消息
                    $this->_doShortvideo($request_xml);
                    break;
                case 'location'://位置消息
                    $this->_doLocation($request_xml);
                    break;
                case 'link'://链接消息
                    $this->_doLink($request_xml);
                    break;
            }
        }
        echo 'success';
        exit;
    }

    //回复文本消息
    private function doText($object)
    {
        $content = '任何问题，请留下您的联系方式，我们会主动联系您';
        $xmlTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        echo  $result;
        exit;
    }

    private function doSubscribe($object){
        $open_id = $object->FromUserName;
        $eventKeyArr = explode('_', $object->EventKey);
        $refer_user_id = $eventKeyArr[1];

        $userModel = UserModel::getSingleton();
        $userInfo = $userModel->find(['open_id'=> $open_id]);
        if(!$userInfo){
            if($refer_user_id){
                //推荐人信息
                $refer_user_info = $userModel->find(['user_id'=> $refer_user_id]);
                if($refer_user_info['user_type'] == 2){
                    $shop_user_id = $refer_user_info['shop_id'];
                }else {
                    $shop_user_id = $refer_user_info['shop_user_id'];
                }

                $addData = [
                    'user_type'         => 0,
                    'unionid'           => 0,
                    'open_id'           => $open_id,
                    'sex'               => 0,
                    'refer_user_id'     => $refer_user_id,
                    'nick_name'         => 0,
                    'head_img'          => 0,
                    'wxcity'            => 0,
                    'shop_user_id'      => $shop_user_id,
                    'shop_id'           => 0,
                    'moble'             => 0,
                    'login_pwd'         => rand(11111111, 99999999),
                    'create_time'       => time()
                ];
                try{
                    $userModel->add($addData);
                }catch(Exception $e){

                }
            }
        }

        $content = '欢迎关注超V购！';
        $xmlTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        echo  $result;
        exit;
    }
    private function doClick($object){

    }
    private function doView($object){

    }
    private function doImage($object){

    }
    private function doVoice($object){

    }
    private function _doVideo($object){

    }
    private function _doShortvideo($object){

    }
    private function _doLocation($object){

    }
    private function _doLink($object){

    }

    private $offline_shop;
    private function searchUserShopByType2($user){
        if(!$user || empty($user)){
            return false;
        }
        //查询推荐店铺
        $userInfo = UserModel::getSingleton()->db
            ->alias('u')
            ->field('u.user_id, u.refer_user_id, s.shop_id, s.shop_type')
            ->join(['shop', 's'], ['u.shop_id'=> 's.shop_id'], 'left join')
            ->where_c(['u.user_id'=> $user['refer_user_id']])
            ->find();

        if($userInfo['shop_type'] != 2){
            $this->searchUserShopByType2($userInfo);
        } else {
            $this->offline_shop = $userInfo;
        }

        return $this->offline_shop ;
    }

    //自定义菜单
    public function menuAction(){
        $wxApp = new \Vendor\ext\Wxapp();
        $data = [
            'button'    => [
                'type'  => 'view',
                'name'  => '超V购',
                'url'   => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8d998a9dfcfaca24&redirect_uri=http%3A%2F%2Fcvgshop.czxb.com%2F&response_type=code&scope=snsapi_userinfo#wechat_redirect'
            ]
        ];

        $str = '{
                 "button":[
                 {    
                      "type":"view",
                      "name":"超V购",
                      "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8d998a9dfcfaca24&redirect_uri=http%3A%2F%2Fcvgshop.czxb.com%2F&response_type=code&scope=snsapi_userinfo#wechat_redirect"
                  }]
                }';

        if(!$wxApp->createMenu( $str )){
            $this->ajaxReturn(400, 'fail');
        }
        $this->ajaxReturn(0, 'success');
    }




    //服务器签名
    public function index1Action(){
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){echo $echoStr;exit;}
    }

    private function checkSignature()
    {

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

}
